<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules">
      <el-form-item required label="项目标签" prop="tags">
        <el-select v-model="formData.tags" multiple placeholder="请选择项目标签" placement="bottom">
          <el-option
            v-for="item in optionTag"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as IctApi from '@/api/project/ict'
import * as DictDataApi from '@/api/system/dict/dict.data'
import { FormRules } from 'element-plus'

import { nextTick, ref } from 'vue'
import type { InputInstance } from 'element-plus'

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('新增案例') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = reactive({
  projectCode: '',
  projectName: '',
  tags: []
})
const formRules = reactive<FormRules>({
  tags: [{ required: true, message: '项目标签不能为空！', trigger: 'change' }]
})

const emit = defineEmits(['success', 'getProjectInfo'])
const formRef = ref()
const props = defineProps({
  editData: {
    type: Object
  }
})

watch(
  () => dialogVisible.value,
  (val) => {
    if (val) {
      getTagData()
      formData.projectCode = props.editData.project_code
      formData.projectName = props.editData.project_name
    }
  },
  { immediate: true }
)

// 获取案例标签
const optionTag = ref([])
const getTagData = () => {
  const params = {
    pageNo: 1,
    pageSize: 100,
    dictType: 'ict_caseLibrary_lable'
  }
  DictDataApi.getDictDataPage(params).then((res) => {
    optionTag.value = res.list
  })
}

// 打开弹窗
const open = async () => {
  resetForm()
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const submitForm = async () => {
  const valid = await formRef.value.validate()
  if (!valid) return
  ElMessageBox.confirm(`确认新增案例【${formData.projectName}】吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 提交请求
      formLoading.value = true
      try {
        if (dialogTitle.value === '新增案例') {
          const params = {
            projectCode: formData.projectCode,
            tags: formData.tags.join(',')
          }
          IctApi.importCase(params).then((res) => {
            if (res.data.data !== -1) {
              ElMessage.success('新增成功！')
            } else {
              ElMessage.error(`${res.data.msg}`)
            }
            // 重置表单
            resetForm()
            formData.tags = []
            dialogVisible.value = false
            emit('success', true)
          })
        }
      } finally {
        formLoading.value = false
      }
    })
    .catch(() => {
      ElMessage.info('已取消新增')
    })
}

// 重置表单
const resetForm = () => {
  formData.projectCode = ''
  formData.projectName = ''
  formData.tags = []
  formRef.value?.resetFields()
}
</script>
<style lang="scss" scoped></style>